package com.njit.office.controller;

import com.njit.office.model.Result;
import com.njit.office.service.FileService;
import com.njit.office.utils.FileUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/api/files")
public class FileController {

    @Resource
    FileService fileService;

    @GetMapping("/{id}")
    @ResponseBody
    public ResponseEntity<FileSystemResource> getFile(@PathVariable("id")String id){

        Result result = fileService.getFile(id);
        File file = (File) result.getData();

        return FileUtils.exportToResponseEntity(file);
    }

    @PostMapping
    public Result uploadFile(@RequestParam("file")MultipartFile multipartFile){

        try {
           return  fileService.saveFile(multipartFile.getInputStream(), multipartFile.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Result();
    }

    @DeleteMapping("/{id}")
    public Result deleteFile(@PathVariable("id")String id) {

        return fileService.deleteFile(id);
    }
}
